class ListNode:

    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:

    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        a = []
        while l1:
            a.append(l1)
            l1 = l1.next
        b = []
        while l2:
            b.append(l2)
            l2 = l2.next
        ans = ListNode()
        c = 0
        while len(a) > 0 and len(b) > 0:
            s = a.pop().val + b.pop().val + c
            c, v = divmod(s, 10)
            node = ListNode(v)
            node.next = ans.next
            ans.next = node
        while len(a) > 0:
            s = a.pop().val + c
            c, v = divmod(s, 10)
            node = ListNode(v)
            node.next = ans.next
            ans.next = node
        while len(b) > 0:
            s = b.pop().val + c
            c, v = divmod(s, 10)
            node = ListNode(v)
            node.next = ans.next
            ans.next = node
        if c != 0:
            node = ListNode(c)
            node.next = ans.next
            ans.next = node
        return ans.next